var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();

//使用mongoose来连接mongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb://193.112.60.83:27017/bank');
mongoose.connection.on("connected", function () {
  console.log("MongoDB connected success.")
});
mongoose.connection.on("error", function () {
  console.log("MongoDB connected fail.")
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'views')));

//路由前的过滤
app.use(function (req,res,next) {
  console.log("url:"+req.originalUrl);
  if(req.originalUrl.indexOf('/role')>-1){//如果含有这个/role路由先判断是否登录
    if (req.originalUrl==='/role/getRoleByName') {
      next()
    }
    else if(req.cookies.token==='lelouch-0001'){
      next()//进入二级路由
    }else {
      res.json({
        status: '0',
        msg: '未登录',
        result: ''
      })
    }
  }else {
    next()
  }
})
//路由开始
app.use('/', indexRouter);
app.use('/users', usersRouter);
var role=require('./routes/role-r');
app.use('/role',role);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
